/*
 * COPYRIGHT. ShenZhen iByte Technology Co., Ltd. 2018.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen iByte Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * Dec 3, 2018    Li.shangzhi         Create the class
 */
package com.github.icloud.elasticsearch.api.search;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.junit.Test;

import com.github.icloud.elasticsearch.ElasticsearchClientBase;
/**
 * @FileName AggregationsAPI.java
 * @Description: 在搜索中添加聚合
 * 
 * 官方文档 @see <a href='https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-aggs.html'></a>
 *
 * @Date Dec 3, 2018 2:28:20 PM
 * @author Li.shangzhi
 * @version 1.0
 */
public class AggregationsAPI extends ElasticsearchClientBase{

	@Test
	public void iEsAggregations() throws Exception{
		SearchResponse srResponse = client.prepareSearch("icloud-alarm","icloud-iot-log")
				.setTypes("icloud-auth","icloud-monitor-alarm")
				.setQuery(QueryBuilders.matchAllQuery())
				.addAggregation(
						AggregationBuilders.terms("agg").field("age")
				)
				.get();
		Terms terms = srResponse.getAggregations().get("agg");
//		System.out.println("数据展示  =================================> START"); 
//		println(srResponse);
//		System.out.println("数据展示  =================================> END"); 
		
		System.out.println(terms.getName());
		for (Terms.Bucket bucket:terms.getBuckets()) {
			System.out.println(bucket.getKey()+">>"+bucket.getDocCount());
		}

		//注意： 可能会报Fielddata is disabled on text fields by default
		//聚合这些操作用单独的数据结构(fielddata)缓存到内存里了，需要单独开启，官方解释在此fielddata
		//https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html

	}
}
